<template>
  <div>
    <div class="content-padding">
      <a-form layout="inline" style="padding: 4px 0px 0px;" :labelCol="{ style: 'width: 78px' }"
        class="nmv-search-form-auto">
        <a-form-item label="车牌号">
          <a-input v-model="grid.queryParams.licensePlate" placeholder="请输入车牌号" class="nmv-w-200" />
        </a-form-item>
        <a-form-item label="车架号">
          <a-input v-model="grid.queryParams.vehicleNo" placeholder="请输入车架号" class="nmv-w-200" />
        </a-form-item>
        <a-form-item label="设备编号">
          <a-input class="nmv-w-200" v-model="grid.queryParams.deviceNo" placeholder="请输入设备编号"></a-input>
        </a-form-item>
        <a-form-item label="资产方">
          <a-select placeholder="全部资产方" allowClear show-search :filter-option="filterOption" @change="searchQuery(1)"
            class=" nmv-w-200" v-model="grid.queryParams.assetId">
            <a-select-option v-for="item in assetList" :key="item.assetId" :value="+item.assetId">{{ item.assetName }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="车辆所有人">
          <a-select class="nmv-w-200" allowClear @change="searchQuery(1)" :filter-option="filterOption" show-search
            placeholder="请选择车辆所有人" v-model="grid.queryParams.belongId">
            <a-select-option v-for="(item, i) in belongAllList" :key="'r_'+i" :value="item.id">{{ item.name }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="运营企业">
          <a-select v-model="grid.queryParams.companyId" @change="agentListGet(grid.queryParams.companyId)"
            placeholder="请选择企业" show-search :filter-option="filterOption" class="nmv-w-200">
            <a-select-option v-for="(item, i) in companiesAllListFilter" :key="'e_'+i" :value="+item.id">{{ item.name }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="运营供应商">
          <a-select v-model="grid.queryParams.agentId" show-search :filter-option="filterOption" placeholder="请选择供应商"
            class="nmv-w-200" @change="searchQuery(1)">
            <a-select-option v-for="(item, i) in agentList" :key="'w_'+i" :value="+item.id">{{ item.name }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="运营门店">
          <a-select placeholder="全部门店" allowClear show-search :filter-option="filterOption" class="nmv-w-200"
            v-model="grid.queryParams.storeId" @change="searchQuery">
            <a-select-option v-for="(item,i) in storeList" :key="'q_'+i" :value="+item.id">{{ item.name }}
            </a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item>
          <a-button type="primary" @click="searchQuery">查询</a-button>

          <a-button style="margin-left:12px" @click="queryReset">重置</a-button>
        </a-form-item>

      </a-form>
      <div class="flex_between_center  text-total" style="padding:0 20px;">

        <div>总数：{{ grid.total }}辆
          <!-- <a-button v-if="selectedRowKey.length > 0" style="margin-left:4px;font-size: 14px;" type="link"
            @click="onResetChange">
            清空
          </a-button> -->
        </div>
        <div>
          <permissions type="vehicle/device/black/export">
            <a-button class="float-r xian_btn" @click="onExport" style="margin-left: 12px;">导出明细</a-button>
          </permissions>
          <permissions type="vehicle/device/black/resume">
            <a-button class="float-r xian_btn" @click="onResumeManyDevice">批量恢复车控</a-button>
          </permissions>

          <!-- <permissions type="vehicle/vehicleManager/garage/export"> -->

          <!-- </permissions> -->
        </div>
      </div>
    </div>
    <div class="content-padding" style="padding-top: 0;">
      <a-table :pagination="false" rowKey="vehicleId" :loading="grid.load" :row-selection="rowSelection"
        :scroll="{ x: 1300 }" :locale="locale" :columns="grid.columns" :data-source="grid.data">

        <span slot="action" slot-scope="text,record">
          <a-popconfirm title="确认要恢复车辆的控制权吗?" ok-text="确定" cancel-text="取消" @confirm="confirm(record)">
            <permissions type="vehicle/device/black/resume"> <a>恢复车控</a></permissions>

          </a-popconfirm>

        </span>
      </a-table>
      <div v-show="grid.total !== 0" style="text-align:right;">
        <a-pagination show-size-changer :current="grid.queryParams.pageNum" :pageSize="grid.queryParams.pageSize"
          @change="onChange" style="margin-top:20px;" size="small" @showSizeChange="onShowSizeChange" :total="grid.total"
          :show-total="total => `共${grid.total}条 `" />
      </div>
    </div>
    <manyResumeDevice ref="manyResumeDeviceRefs" @close="searchQuery(1)" />
  </div>
</template>
<script>
import {
  getAllStore,
  companiesAllList,
  agentList,
  companiesPresonList
} from '@/services/rider'
import { deviceBlackList, resumeDevice, blackListExport } from '@/services/car'
import { assetListAll } from '@/services/store'
import Empty from '@/components/Empty/Empty'
import manyResumeDevice from './Dialog/manyResumeDevice.vue'
import { downLoads } from '@/utils/util.js'
import permissions from '@/components/permissions'
export default {
  components: { manyResumeDevice, permissions },
  created () {
    this.parentCompanyIdGet()
    this.getCompaniesAllList()
    this.getAllasset()
    this.getList()
    this.getListPerson()
  },
  computed: {
    rowSelection () {
      return {
        fixed: true,
        // onSelectChange (selectedRowKeys, selected) {
        //   console.log('selectedRowKeys selected: ', selected)
        //   this.selectedRowKeys = selectedRowKeys
        // },
        onChange: (selectedRowKeys, selected) => {
          this.selectedRowKeys = selectedRowKeys
          const params = this.selectedRowKey.concat(selected)

          const map = {}
          const data = []
          params.forEach(el => {
            if (!map[JSON.stringify(el)]) {
              map[JSON.stringify(el)] = true
              data.push(el)
            }
          })
          console.log(this.selectedRowKeys, 'data')
          this.selectedRowKey = data.filter(ele => {
            return this.selectedRowKeys.find(prop => {
              return prop === ele.vehicleId
            })
          })
        },
        selectedRowKeys: this.selectedRowKeys,
        getCheckboxProps: record => ({
          props: {
            // disabled: record.outBound === 2 // Column configuration not to be checked
          }
        })
      }
    }
  },
  data () {
    return {
      locale: {
        emptyText: <Empty />
      },
      selectedRowKeys: [],
      selectedRowKey: [],
      belongAllList: [],
      assetList: [],
      companiesAllListFilter: [],
      agentList: [],
      storeList: [],
      grid: {
        load: false,
        total: 0,
        queryParams: {
          pageNum: 1,
          pageSize: 10
        },
        columns: [
          {
            title: '车牌号',
            dataIndex: 'licensePlate',
            key: 'licensePlate',
            width: 110,
            ellipsis: true,
            customRender: (text, record) => <a onClick={() => this.toCarDetail(record)}>{text}</a>
          },
          {
            title: '车架号/设备编号',
            dataIndex: 'deviceNo',
            key: 'deviceNo',
            width: 240,
            customRender: (text, record) =>
              <div style="display:flex;flex-direction:column;">
                <p style="font-size:14px;margin-bottom:5px;"><span style="color:#999999">车架号：</span>{record.vehicleNo || '-'}</p>
                <p style="font-size:14px;margin:0"><span style="color:#999999">设备编号：</span>{record.deviceNo || '-'}</p>
              </div>
          },
          {
            title: '资产方/所有人',
            dataIndex: 'fundManagerName',
            key: 'fundManagerName',
            width: 210,
            customRender: (text, record) =>
              <div style="display:flex;flex-direction:column;">
                <p style="font-size:14px;margin-bottom:5px;"><span style="color:#999999">资产方：</span>{record.fundManagerName || '-'}</p>
                <p style="font-size:14px;margin:0"><span style="color:#999999">所有人：</span>{record.belongName || '-'}</p>
              </div>
          },
          {
            title: '运营企业/供应商',
            dataIndex: 'companyName',
            key: 'companyName',
            width: 180,
            ellipsis: true,
            customRender: (text, record) =>
              <div style="display:flex;flex-direction:column;">
                <p style="font-size:14px;margin-bottom:5px;"><span style="color:#999999">运营商：</span>{record.companyName || '-'}</p>
                <p style="font-size:14px;margin:0"><span style="color:#999999">供应商：</span>{record.agentName || '-'}</p>
              </div>
          },
          {
            title: '运营门店',
            dataIndex: 'storeName',
            key: 'storeName',
            width: 180,
            ellipsis: true,
            customRender: (text) => text || '-'
          },
          {
            title: '操作人',
            dataIndex: 'operatorName',
            key: 'operatorName',
            width: 170,
            customRender: (text, record) =>
              <div style="display:flex;flex-direction:column;">
                <p style="font-size:14px;margin-bottom:5px;">{record.operatorName || '-'}</p>
                <p style="font-size:14px;margin:0">{record.operatorTime || '-'}</p>
              </div>
          },
          {
            title: '备注信息',
            dataIndex: 'remark',
            key: 'remark',
            width: 160,
            ellipsis: true,
            customRender: (text) => text || '-'
          }, {
            title: '操作',
            dataIndex: 'action',
            key: 'action',
            fixed: 'right',
            width: 110,
            scopedSlots: { customRender: 'action' }
          }
        ],
        data: []
      }
    }
  },
  methods: {
    async onExport () {
      const res = await blackListExport(this.grid.queryParams)
      downLoads('中控黑名单列表.xlsx', res)
    },
    // 批量恢复
    onResumeManyDevice () {
      console.log(this.selectedRowKeys, 'this.selectedRowKeys')
      if (this.selectedRowKeys.length > 0) {
        this.$refs.manyResumeDeviceRefs.open({ arr: this.selectedRowKeys })
      } else {
        this.$message.newFun('请至少选择一辆车', 'error', 3)
      }
    },
    toCarDetail (record) {
      window.open(`/#/vehicle/vehicleManager/vehicleList?vehiclePlate=${record.licensePlate}&id=${record.vehicleId}`)
    },
    // 恢复车控
    async confirm (record) {
      console.log(record)
      const arr = []
      arr.push(record.vehicleId)
      const res = await resumeDevice({ vehicleIds: arr })
      if (res.isSuccess) {
        this.$message.newFun('操作成功！', 'success', 3)
        this.searchQuery()
      } else {
        this.$message.newFun(res.msg, 'error', 3)
      }
    },
    async getList () {
      this.grid.load = true
      const res = await deviceBlackList(this.grid.queryParams)
      const { isSuccess, data: response, msg } = res
      if (isSuccess) {
        this.grid.data = response.records
        this.grid.total = response.total
        this.grid.load = false
      } else {
        this.$message.newFun(msg, 'error', 2)
        this.grid.data = []
        this.grid.total = 0
        this.grid.load = false
      }
    },
    onResetChange () {
      this.selectedRowKeys = []
      this.selectedRowKey = []
    },
    async getListPerson () {
      const res = await companiesPresonList({
        name: ''
      })
      const { isSuccess, data: response, msg } = res
      if (isSuccess) {
        this.belongAllList = response
      } else {
        this.$message.newFun(msg, 'error', 2)
      }
    },
    async getCompaniesAllList () {
      const res = await companiesAllList()
      const { isSuccess, data: response, msg } = res
      if (isSuccess) {
        this.companiesAllListFilter = response
      } else {
        this.$message.newFun(msg, 'error', 2)
      }
    },
    async agentListGet (id) {
      const res = await agentList(id)
      const { isSuccess, data: response, msg } = res
      if (isSuccess) {
        this.agentList = response
      } else {
        this.$message.newFun(msg, 'error', 2)
      }
    },
    parentCompanyIdGet () {
      getAllStore().then((res) => {
        const { isSuccess, data: response, msg } = res
        if (isSuccess) {
          this.storeList = response
        } else {
          this.$message.newFun(msg, 'error', 2)
        }
      }).catch((err) => {
        console.log(err)
      })
    },
    async getAllasset () {
      const res = await assetListAll()
      const { isSuccess, data: response, msg } = res
      if (isSuccess) {
        this.assetList = response
      } else {
        this.$message.newFun(msg, 'error', 2)
      }
    },
    filterOption (input, option) {
      return (
        option.componentOptions.children[0].text
          .toLowerCase()
          .indexOf(input.toLowerCase()) >= 0
      )
    },
    onChange (page, pageSize) {
      this.grid.queryParams.pageNum = page
      console.log(pageSize)
      this.searchQuery()
    },
    onShowSizeChange (current, pageSize) {
      this.grid.queryParams.pageSize = pageSize
      this.grid.queryParams.pageNum = 1
      console.log(current)
      this.searchQuery()
    },
    searchQuery (type) {
      if (type) {
        this.grid.queryParams.pageNum = 1
        this.grid.queryParams.pageSize = 10
      }
      this.getList()
    },
    // 重置
    queryReset () {
      this.selectedRowKeys = []
      this.selectedRowKey = []
      this.grid.queryParams = {
        pageNum: 1,
        pageSize: 10
      }
      this.getList()
    }
  }

}
</script>
